package com.blueocean_health.care.management.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.blueocean_health.care.management.common.base.em.TimeType;
import com.blueocean_health.care.management.common.base.string.StringUtils;
import com.blueocean_health.care.management.common.base.time.TimeUtils;
import com.blueocean_health.care.management.domain.base.Hospital;
import com.blueocean_health.care.management.domain.base.Selectzhdzlist;
import com.blueocean_health.care.management.domain.dto.OrderInfoPriceDto;
import com.blueocean_health.care.management.domain.dto.OrderInfoPriceRespDto;
import com.blueocean_health.care.management.domain.dto.OrderSelectInfoEntity;
import com.blueocean_health.care.management.domain.dto.SelectCareSalaryDto;
import com.blueocean_health.care.management.domain.dto.SelectCareSalaryRespDto;
import com.blueocean_health.care.management.domain.ordervo.SelectZHDZVo;
import com.blueocean_health.care.management.em.OrderTypeEnum;
import com.blueocean_health.care.management.exception.OrderServiceException;
import com.blueocean_health.care.management.mapper.SelectzhdzlistMapper;
import com.blueocean_health.care.management.service.HospitalService;
import com.blueocean_health.care.management.service.OrderInfoPriceService;
import com.blueocean_health.care.management.service.SelectZHDZService;
import com.blueocean_health.care.management.service.order_service_info.SelectCareSalaryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@Service
public class SelectZHDZServiceImpl implements SelectZHDZService{
	@Autowired
	private SelectzhdzlistMapper selectzhdzlistMapper;
	@Autowired
	private OrderInfoPriceService orderInfoPriceService;
	@Autowired 
	private SelectCareSalaryService selectCareSalaryService;
	@Autowired
	private HospitalService hospitalService;
	/**
	 * 查询综合对账表
	 */
	@Override
	
	public Map<String, Object> selectOrderList(SelectZHDZVo selectZHDZVo) throws OrderServiceException{
	
		
		if(!StringUtils.isEmpty(selectZHDZVo.getBeginTime())){
			selectZHDZVo.setBeginTime(selectZHDZVo.getBeginTime()+" 00:00:00");
		}
		if(!StringUtils.isEmpty(selectZHDZVo.getEndTime())){
			selectZHDZVo.setEndTime(selectZHDZVo.getEndTime()+" 23:59:59");
		}
		String minReceiptNumber = selectZHDZVo.getMinReceiptNumber();
		String maxReceiptNumber = selectZHDZVo.getMaxReceiptNumber();
		//如果等于空查询全量的数据
		
		if(!StringUtils.isEmpty(minReceiptNumber)){
			Pattern pattern = Pattern.compile("\\d+");  
			boolean flag=pattern.matcher(minReceiptNumber).matches();  
			if(!flag){
				Map<String, Object> pageInfo = new HashMap<>();
				pageInfo.put("total", 0);
				
				Map<String, Object> map=new HashMap<String, Object>();
				map.put("pageInfo", pageInfo);
				map.put("list", new ArrayList<>());
				map.put("patientCount", 0);
				map.put("sumReceipt", 0);
				map.put("sumTotalPay", 0);
				return map;
			}
		}
		if(!StringUtils.isEmpty(maxReceiptNumber)){
			Pattern pattern = Pattern.compile("\\d+");  
			boolean flag=pattern.matcher(maxReceiptNumber).matches();  
			if(!flag){
				Map<String, Object> pageInfo = new HashMap<>();
				pageInfo.put("total", 0);
				
				Map<String, Object> map=new HashMap<String, Object>();
				map.put("pageInfo", pageInfo);
				map.put("list", new ArrayList<>());
				map.put("patientCount", 0);
				map.put("sumReceipt", 0);
				map.put("sumTotalPay", 0);
				return map;
			}
		}
		PageHelper.startPage(Integer.valueOf(StringUtils.isEmpty(selectZHDZVo.getPage())?"1":selectZHDZVo.getPage()),Integer.valueOf(StringUtils.isEmpty(selectZHDZVo.getPageSize())?"65536":selectZHDZVo.getPageSize()));
		List<Selectzhdzlist> selectzhdzlist = selectzhdzlistMapper.selectzhdzlist(selectZHDZVo);
		for (Selectzhdzlist selectzhdzlist2 : selectzhdzlist) {
			String departmentFB = toDepartmentAndTime(selectzhdzlist2);
			selectzhdzlist2.setDepartmentFB(departmentFB);
		//	getstandardprice(selectzhdzlist2);
		//	getgroupName(selectzhdzlist2);
			getDayHour(selectzhdzlist2);
		}
		
		
		PageInfo<Selectzhdzlist> pageInfo = new PageInfo<Selectzhdzlist>(selectzhdzlist);
		
		//患者总数
		int selectPatientZhdzCount = selectzhdzlistMapper.selectPatientZhdzCount(selectZHDZVo);
		
		//收据金额
		double selectPriceZhdzSum = selectzhdzlistMapper.selectPriceZhdzSum(selectZHDZVo);
		
		//提成金额
		double selectPayZhdzSum = selectzhdzlistMapper.selectPayZhdzSum(selectZHDZVo);
		
		Map<String, Object> pageInfomap = new HashMap<>();
		pageInfomap.put("total", pageInfo.getTotal());
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("pageInfo", pageInfomap);
		map.put("list",pageInfo.getList());
		map.put("patientCount", selectPatientZhdzCount);
		map.put("sumReceipt", selectPriceZhdzSum);
		map.put("sumTotalPay", selectPayZhdzSum);
		return map;
	}
	/**
	 * 查询综合对账表新
	 */
	@Override
	
	public Map<String, Object> selectOrderListNew(SelectZHDZVo selectZHDZVo) throws OrderServiceException{
		if(!StringUtils.isEmpty(selectZHDZVo.getBeginTime())){
			selectZHDZVo.setBeginTime(selectZHDZVo.getBeginTime()+" 00:00:00");
		}
		if(!StringUtils.isEmpty(selectZHDZVo.getEndTime())){
			selectZHDZVo.setEndTime(selectZHDZVo.getEndTime()+" 23:59:59");
		}
		String serviceBeginTime = selectZHDZVo.getServiceBeginTime();
		String serviceEndTime = selectZHDZVo.getServiceEndTime();
		if(!StringUtils.isEmpty(selectZHDZVo.getServiceBeginTime())){
			selectZHDZVo.setServiceBeginTime(selectZHDZVo.getServiceBeginTime()+" 00:00:00");
		}
		if(!StringUtils.isEmpty(selectZHDZVo.getServiceEndTime())){
			selectZHDZVo.setServiceEndTime(selectZHDZVo.getServiceEndTime()+" 00:00:00");
		}
		String minReceiptNumber = selectZHDZVo.getMinReceiptNumber();
		String maxReceiptNumber = selectZHDZVo.getMaxReceiptNumber();
		//如果等于空查询全量的数据
		
		if(!StringUtils.isEmpty(minReceiptNumber)){
			Pattern pattern = Pattern.compile("\\d+");  
			boolean flag=pattern.matcher(minReceiptNumber).matches();  
			if(!flag){
				Map<String, Object> pageInfo = new HashMap<>();
				pageInfo.put("total", 0);
				
				Map<String, Object> map=new HashMap<String, Object>();
				map.put("pageInfo", pageInfo);
				map.put("list", new ArrayList<>());
				map.put("patientCount", 0);
				map.put("sumReceipt", 0);
				map.put("sumTotalPay", 0);
				return map;
			}
		}
		//如果等于空查询全量的数据
		if(!StringUtils.isEmpty(maxReceiptNumber)){
			Pattern pattern = Pattern.compile("\\d+");  
			boolean flag=pattern.matcher(maxReceiptNumber).matches();  
			if(!flag){
				Map<String, Object> pageInfo = new HashMap<>();
				pageInfo.put("total", 0);
				
				Map<String, Object> map=new HashMap<String, Object>();
				map.put("pageInfo", pageInfo);
				map.put("list", new ArrayList<>());
				map.put("patientCount", 0);
				map.put("sumReceipt", 0);
				map.put("sumTotalPay", 0);
				return map;
			}
		}
		String hospitalId = selectZHDZVo.getHospitalId();
	//	Hospital hospital = hospitalService.getHospitalInfo(hospitalId);
	//	selectZHDZVo.setCountMethod(hospital.getCountMethod());
		 
		PageHelper.startPage(Integer.valueOf(StringUtils.isEmpty(selectZHDZVo.getPage())?"1":selectZHDZVo.getPage()),Integer.valueOf(StringUtils.isEmpty(selectZHDZVo.getPageSize())?"65536":selectZHDZVo.getPageSize()));
		List<Selectzhdzlist> selectzhdzlist = selectzhdzlistMapper.selectzhdzlist(selectZHDZVo);
		boolean flag=!StringUtils.isEmpty(serviceBeginTime)&&!StringUtils.isEmpty(serviceEndTime);
		//调用提成表的接口
		List<SelectCareSalaryRespDto> queryCareSalaryReportExcel=null;
		if(flag){
		SelectCareSalaryDto selectCareSalaryDto=new SelectCareSalaryDto();
		selectCareSalaryDto.setBeginTime(serviceBeginTime);
		selectCareSalaryDto.setEndTime(serviceEndTime);
		selectCareSalaryDto.setHospitalId(hospitalId);
		selectCareSalaryDto.setWorkerKey(selectZHDZVo.getWorkName());
//		queryCareSalaryReportExcel = selectCareSalaryService.queryCareSalaryReportExcel(selectCareSalaryDto);
		}
		for (Selectzhdzlist selectzhdzlist2 : selectzhdzlist) {
			String departmentFB = toDepartmentAndTime(selectzhdzlist2);
			selectzhdzlist2.setDepartmentFB(departmentFB);
			//调用接口返回提成数据
		//	if(flag&&null!=queryCareSalaryReportExcel&&queryCareSalaryReportExcel.size()>0){
			if(flag){
//			selectzhdzlist2.setTotalPay(0.0);
//			for (SelectCareSalaryRespDto selectCareSalaryRespDto : queryCareSalaryReportExcel) {
//				//同一serviceid想加
//				if(selectzhdzlist2.getServiceId().equals(selectCareSalaryRespDto.getServiceId())){
//					selectzhdzlist2.setTotalPay(selectzhdzlist2.getTotalPay()+Double.valueOf(selectCareSalaryRespDto.getDayPay()));
//				}
//			}
			toCaiPrice(selectzhdzlist2, selectZHDZVo);
			tototalPay(selectzhdzlist2, selectZHDZVo);
			}else{
				selectzhdzlist2.setJianCaiPrice(selectzhdzlist2.getActualTotalPrice());
			}
			getDayHour(selectzhdzlist2);
		}
		PageInfo<Selectzhdzlist> pageInfo = new PageInfo<Selectzhdzlist>(selectzhdzlist);
//		Map<String, String> map1=new HashMap<String, String>();
		
		
		//患者总数
		int selectPatientZhdzCount = selectzhdzlistMapper.selectPatientZhdzCount(selectZHDZVo);
		
		//收据金额
		double selectPriceZhdzSum = selectzhdzlistMapper.selectPriceZhdzSum(selectZHDZVo);
		
		//收款金额
		double selectZhdzJianCaiPrice = selectzhdzlistMapper.selectZhdzJianCaiPrice(selectZHDZVo);
		
		//提成金额
		//double selectPayZhdzSum = selectzhdzlistMapper.selectPayZhdzSum(selectZHDZVo);
		double selectPayZhdzSum=0.0;
//		List<String> selectZhdzAllServiceId = selectzhdzlistMapper.selectZhdzAllServiceId(selectZHDZVo);
//		if(null!=selectZhdzAllServiceId&&selectZhdzAllServiceId.size()>0&&flag&&null!=queryCareSalaryReportExcel&&queryCareSalaryReportExcel.size()>0){
//		for (SelectCareSalaryRespDto selectCareSalaryRespDto : queryCareSalaryReportExcel){
//		for (String serviceId : selectZhdzAllServiceId) {
//				if(serviceId.equals(selectCareSalaryRespDto.getServiceId())){
//					selectPayZhdzSum+=Double.valueOf(selectCareSalaryRespDto.getDayPay());
//				}
//			}
//		}
		if(flag){
			List<Selectzhdzlist> selectzhdzlistall = selectzhdzlistMapper.selectzhdzlist(selectZHDZVo);
			
			 selectPayZhdzSum = selectzhdzlistall.stream().map(s->tototalPay(s, selectZHDZVo)).mapToDouble(p->p.getTotalPay()).sum();
		}else{
			selectPayZhdzSum = selectzhdzlistMapper.selectPayZhdzSum(selectZHDZVo);
		}
		
		BigDecimal   b   =   new   BigDecimal(selectPayZhdzSum);  
		selectPayZhdzSum  =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();  
		
		Map<String, Object> pageInfomap = new HashMap<>();
		pageInfomap.put("total", pageInfo.getTotal());
		Map<String, Object> map=new HashMap<String, Object>(); 
		map.put("pageInfo", pageInfomap);
		map.put("list",pageInfo.getList());
		map.put("patientCount", selectPatientZhdzCount);
		map.put("sumReceipt", selectPriceZhdzSum);
		map.put("sumTotalPay", selectPayZhdzSum);
		map.put("jianCaiPrice", selectZhdzJianCaiPrice);
		return map;
	}
	private Selectzhdzlist toCaiPrice(Selectzhdzlist selectzhdzlist,SelectZHDZVo selectZHDZVo){
		 long nd = 1000 * 24 * 60 * 60;
		Integer caiDay = selectzhdzlist.getCaiDay();
		 Integer caiHour = selectzhdzlist.getCaiHour();
		Double actualDayPrice = selectzhdzlist.getActualDayPrice();
		Double oneHourPrice = selectzhdzlist.getOneHourPrice();
		Double actualTotalPrice = selectzhdzlist.getActualTotalPrice();
		Double caiPrice= (caiDay*actualDayPrice)+(caiHour*oneHourPrice);
		//筛选开始时间
		Date serviceBeginTimeByString = TimeUtils.getDateByString(selectZHDZVo.getServiceBeginTime(),TimeType.yyyy_MM_dd_HH_mm_ss);
		Date serviceEndTimeByString = TimeUtils.getDateByString(selectZHDZVo.getServiceEndTime(),TimeType.yyyy_MM_dd_HH_mm_ss);
		//订单开始时间
		Date beginTimes = selectzhdzlist.getBeginTimes();
		Date endTimes = selectzhdzlist.getEndTimes();
		//当订单的开始时间小于查询条件的开始时间，订单的服务结束时间小于查询条件的结束时间 减法
		if(beginTimes.getTime()<serviceBeginTimeByString.getTime()&&endTimes.getTime()<=serviceEndTimeByString.getTime()+1*nd){
			 int day = (int) ((serviceBeginTimeByString.getTime() -beginTimes.getTime())/nd);
			 double oldprice = day*actualDayPrice;
			 BigDecimal actualTotalPriceb = new BigDecimal(Double.toString(actualTotalPrice));
			 BigDecimal oldpriceb = new BigDecimal(Double.toString(oldprice));
			caiPrice=actualTotalPriceb.subtract(oldpriceb).doubleValue();
		}
		//当订单的开始时间大于查询条件的开始时间，订单的服务结束时间小于查询条件的结束时间 直接取
		if(beginTimes.getTime()>=serviceBeginTimeByString.getTime()&&endTimes.getTime()<=serviceEndTimeByString.getTime()+1*nd){
		
			caiPrice=actualTotalPrice;
		}
		selectzhdzlist.setJianCaiPrice(caiPrice);
		selectzhdzlist.setDay(caiDay+"."+caiHour);
		 return selectzhdzlist;
		
		
	}
	
	private static Selectzhdzlist tototalPay(Selectzhdzlist selectzhdzlist,SelectZHDZVo selectZHDZVo){
		 long nd = 1000 * 24 * 60 * 60;
		Integer caiDay = selectzhdzlist.getCaiDay();
		 Integer caiHour = selectzhdzlist.getCaiHour();
		Double totalPay = selectzhdzlist.getTotalPay();
		 Double oneHourPay = selectzhdzlist.getOneHourPay();
		 Double oneDayPay = selectzhdzlist.getOneDayPay();
		Double caipay= (caiDay*oneDayPay)+(caiHour*oneHourPay);
		//筛选开始时间
		Date serviceBeginTimeByString = TimeUtils.getDateByString(selectZHDZVo.getServiceBeginTime(),TimeType.yyyy_MM_dd_HH_mm_ss);
		Date serviceEndTimeByString = TimeUtils.getDateByString(selectZHDZVo.getServiceEndTime(),TimeType.yyyy_MM_dd_HH_mm_ss);
		//订单开始时间
		Date beginTimes = selectzhdzlist.getBeginTimes();
		Date endTimes = selectzhdzlist.getEndTimes();
		//当订单的开始时间小于查询条件的开始时间，订单的服务结束时间小于查询条件的结束时间 减法
		if(beginTimes.getTime()<serviceBeginTimeByString.getTime()&&endTimes.getTime()<=serviceEndTimeByString.getTime()+1*nd){
			 int day = (int) ((serviceBeginTimeByString.getTime() -beginTimes.getTime())/nd);
			 double oldpay = day*oneDayPay;
			 BigDecimal actualTotalPayb = new BigDecimal(Double.toString(totalPay));
			 BigDecimal oldpayb = new BigDecimal(Double.toString(oldpay));
			 caipay=actualTotalPayb.subtract(oldpayb).doubleValue();
		}
		//当订单的开始时间大于查询条件的开始时间，订单的服务结束时间小于查询条件的结束时间 直接取
		if(beginTimes.getTime()>=serviceBeginTimeByString.getTime()&&endTimes.getTime()<=serviceEndTimeByString.getTime()+1*nd){
		
			caipay=totalPay;
		}
		selectzhdzlist.setTotalPay(caipay);
		 return selectzhdzlist;
		
		
	}
	/**
	 * 导出excel
	 */
	@Override
	public List<Selectzhdzlist> selectOrderexcel(SelectZHDZVo selectZHDZVo) throws OrderServiceException{
		if(!StringUtils.isEmpty(selectZHDZVo.getBeginTime())){
			selectZHDZVo.setBeginTime(selectZHDZVo.getBeginTime()+" 00:00:00");
		}
		if(!StringUtils.isEmpty(selectZHDZVo.getEndTime())){
			selectZHDZVo.setEndTime(selectZHDZVo.getEndTime()+" 23:59:59");
		}
		List<Selectzhdzlist> selectzhdzlist = selectzhdzlistMapper.selectzhdzlist(selectZHDZVo);
		for (Selectzhdzlist selectzhdzlist2 : selectzhdzlist) {
			String departmentFB = toDepartmentAndTime(selectzhdzlist2);
			selectzhdzlist2.setDepartmentFB(departmentFB);
			//getstandardprice(selectzhdzlist2);
			//getgroupName(selectzhdzlist2);
			getDayHour(selectzhdzlist2);
		}
		
		return selectzhdzlist;
	}
	/**
	 * 拼接科室和其他
	 * @param selectzhdz
	 * @return
	 */
	private String toDepartmentAndTime(Selectzhdzlist selectzhdz) {
		String departmentName = StringUtils.isEmpty(selectzhdz.getDeptName()) ? ""
				: selectzhdz.getDeptName();
		String buildingName = StringUtils.isEmpty(selectzhdz.getBuildingName()) ? ""
				: selectzhdz.getBuildingName();
		String floorName = StringUtils.isEmpty(selectzhdz.getFloorName()) ? ""
				: selectzhdz.getFloorName();
		String departmentFB = buildingName + "-" + floorName +"-"+ departmentName ;
		return departmentFB;

	}
	/**
	 * 调取资费标准
	 * @param selectzhdz
	 * @throws OrderServiceException
	 */
  private void getstandardprice(Selectzhdzlist selectzhdz) throws OrderServiceException{
	  OrderInfoPriceDto orderInfoPriceDto=new OrderInfoPriceDto();
	  orderInfoPriceDto.setHid(selectzhdz.getHospitalId());
	  orderInfoPriceDto.setDepartment(String.valueOf(selectzhdz.getDepartment()));
	  orderInfoPriceDto.setIllnessGrade(selectzhdz.getIllnessGrade());
	  orderInfoPriceDto.setServiceType(selectzhdz.getServiceType());
	  orderInfoPriceDto.setTimetypeId("1");
	  OrderInfoPriceRespDto findPricenew = orderInfoPriceService.findPricenew(orderInfoPriceDto);
	  if(selectzhdz.getOrderType().equals(OrderTypeEnum._3.getKey())){
		  selectzhdz.setStandardOneHourPay(findPricenew.getHourPay()==0?0:findPricenew.getHourPay()*-1);
		  selectzhdz.setStandardoneDayPay(findPricenew.getOneDayPay()==0?0:findPricenew.getOneDayPay()*-1);
		  selectzhdz.setStandardOneHourPrice(findPricenew.getHourPrice()==0?0:findPricenew.getHourPrice()*-1);
		  selectzhdz.setStandardOneDayPrice(findPricenew.getOneDayPrice()==0?0:findPricenew.getOneDayPrice()*-1);
	  }else{
	  selectzhdz.setStandardOneHourPay(findPricenew.getHourPay());
	  selectzhdz.setStandardoneDayPay(findPricenew.getOneDayPay());
	  selectzhdz.setStandardOneHourPrice(findPricenew.getHourPrice());
	  selectzhdz.setStandardOneDayPrice(findPricenew.getOneDayPrice());
	  }
  }
  

 //构建小时服务时长
  private void getDayHour(Selectzhdzlist selectzhdzlist){
	  	String dayhour = selectzhdzlist.getDay();
		String[] split = dayhour.split("\\.");
		String daystr = split[0];
		String hourstr="0";
		if(split.length>1){
			hourstr=split[1];
		}
		String day="";
		if(!daystr.equals("0")){
			day=daystr+"天";
		}
		if(!hourstr.equals("0")){
			day+=hourstr+"小时";
		}
		selectzhdzlist.setDay(day);
	  
  }
//拼接小组字段
//private void getgroupName (Selectzhdzlist selectzhdzlist){
//	String groupNamess = selectzhdzlist.getGroupNames();
//	if(!StringUtils.isEmpty(groupNamess)){
//		String workerNames = selectzhdzlist.getWorkerNames();
//		if(!StringUtils.isEmpty(workerNames)){
//			selectzhdzlist.setWorkerNames(workerNames+"/"+groupNamess);
//		}else{
//			selectzhdzlist.setWorkerNames(groupNamess);
//		}
//		
//	};

}